#region Telligent Copyright Header

//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

#endregion

#region Import Declarations

using System.IO;
using System;
using System.Security;
using System.Collections;
using System.Xml;
using CommunityServer.Components;
using System.Collections.Generic;
using CommunityServer.Blogs.Components;
using CommunityServer.Blogs;

#endregion

namespace CommunityServerStuff.CSModules
{
    class AutoBlogCreateInRoleGroup : ICSModule
    {

        #region Private Members

        private Hashtable roleMappings = new Hashtable();

        #endregion

        #region Methods

        #region Constructor

        public AutoBlogCreateInRoleGroup() { }

        #endregion

        #region Init

        public void Init(CSApplication csa, XmlNode node)
		{
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.Name == "RoleMapping")
                {
                    roleMappings.Add(childNode.Attributes["RoleName"].Value.ToLower(), int.Parse(childNode.Attributes["GroupId"].Value));
                }
            }
			csa.PostUserUpdate += new CSUserEventHandler(csa_PostUserUpdate);
        }

        #endregion

        #region csa_PostUserUpdate

        private void csa_PostUserUpdate(User user, CSEventArgs e)
		{
			if(user != null && e.State == ObjectState.Update)
			{
                if (user.GetExtendedAttribute("blogAutoCreated").Equals(string.Empty) || bool.Parse(user.GetExtendedAttribute("blogAutoCreated")))
                {
                    return;
                }

                WeblogConfiguration config = WeblogConfiguration.Instance();
                if (config.EnableAutoCreate)
				{
                    string formattedKey = null;
                    Globals.ValidateApplicationKey(user.Username, out formattedKey);

                    if (Globals.IsNullorEmpty(formattedKey) || Weblogs.Exists(formattedKey, -1))
                    {
                        return;
                    }
                    Weblog w = new Weblog();
                    w.ApplicationKey = formattedKey;

                    int groupid = config.DefaultGroupID;

                    foreach (string r in roleMappings.Keys)
                    {
                        if (System.Web.Security.Roles.IsUserInRole(user.Username, r))
                        {
                            groupid = (int)roleMappings[r];
                            EventLogs.Warn("RoleMapping found. Role: " + roleMappings[r].ToString(), "RoleGalleryCreate", 941);
                            break;
                        }
                    }
                    
                    if (groupid <= 0)
                    {
                        List<Group> groups = WeblogGroups.GetWeblogGroups(true, false, false);
                        if (groups.Count > 0)
                            groupid = ((Group)groups[0]).GroupID;
                    }

                    if (groupid <= 0)
                        return;

                    //Set remaining section settings
                    w.GroupID = groupid;
                    w.Name = user.Username;
                    w.IsActive = true;
                    w.SettingsID = CSContext.Current.SiteSettings.SettingsID;
                    w.ApplicationType = ApplicationType.Weblog;


                    w.Owners = user.Username;
                    w.IsSearchable = true;
                    w.EnableAggBugs = true;
                    w.IsCommunityAggregated = true;

                    // Create The Blog
                    w.SectionID = Weblogs.Add(w);

                    // Assign the blog address to the user's profile if 
                    // there is not currently one assigned to them.
                    if (Globals.IsNullorEmpty(user.Profile.WebLog))
                    {
                        user.Profile.WebLog = Globals.FullPath(w.Url);
                        user.SetExtendedAttribute("blogAutoCreated", "true");
                    }

                    if (config.CreateBlogDirectories)
                        Weblogs.CreateBlogDirectory(w);
				}
			}
        }

        #endregion

        #endregion
    }
}
